package com.auto.api.common.utils;

import com.auto.api.common.exception.BusinessException;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: api-mommon
 * @description: json工具类
 * @author: liangshf
 * @create: 2021-12-24
 */
public class JsonMapper {

    private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);

    private static ObjectMapper objectMapper  = new ObjectMapper();

    static {
        //非空对象
        objectMapper.setSerializationInclusion(Include.NON_NULL);
        // 忽略字符串中存在，Java对象中没有的属性
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        //忽略空Bean转json的错误
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(LocalDateTimeUtils.dateFormatter));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(LocalDateTimeUtils.dateFormatter));
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(LocalDateTimeUtils.dateTimeFormatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(LocalDateTimeUtils.dateTimeFormatter));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(LocalDateTimeUtils.timeFormatter));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(LocalDateTimeUtils.timeFormatter));
        objectMapper.registerModule(javaTimeModule);
    }

    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            logger.error("JSON error: {}", object, e);
            throw new BusinessException("JSON error", e);
        }
    }

    /**
     * 构造Collection类型.
     */
    public static JavaType constructCollectionType(Class<? extends Collection> collectionClass,
        Class<?> elementClass) {
        return objectMapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
    }

    /**
     * 构造Map类型.
     */
    public static JavaType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass,
        Class<?> valueClass) {
        return objectMapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
    }

    /**
     * 反序列化POJO或简单Collection如List<?>.
     *
     * 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
     *
     * 如需反序列化复杂Collection如List<?>, 请使用fromJson(String, JavaType)
     *
     * @see #fromJson(String, JavaType)
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }

        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            logger.error("JSON反序列化异常: %s", json, e);
            throw new BusinessException("JSON反序列化异常: {}" ).args(json);
        }
    }

    /**
     * 反序列化复杂Collection如List<?>, 先使用createCollectionType()或contructMapType()构造类型, 然后调用本函数.
     */
    public static <T> T fromJson(String jsonString, JavaType javaType) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }

        try {
            return (T) objectMapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            logger.error("JSON反序列化异常: {}", jsonString, e);
            throw new BusinessException("JSON反序列化异常: " + jsonString);
        }
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static <T> T fromJson(String jsonString, TypeReference type) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            return (T) objectMapper.readValue(jsonString, type);
        } catch (IOException e) {
            logger.error("JSON反序列化异常:{}", jsonString, e);
            throw new BusinessException("JSON反序列化异常: " + jsonString);
        }
    }

    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

}